{% extends 'base.attached.class' %}

{% block content %}
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define N_FEATURES {{ n_features }}
#define N_CLASSES {{ n_classes }}


int find_max(int nums[N_CLASSES]) {
    int i;  int idx = 0;
    for (i = 0; i < N_CLASSES; i++) {
        idx = nums[i] > nums[idx] ? i : idx;
    }
    return idx;
}

void norm_vals(double *result, int nums[N_CLASSES]) {
    int i;  double sum = 0.;
    for (i = 0; i < N_CLASSES; i++) {
        sum += nums[i];
    }
    if(sum == 0) {
        for (i = 0; i < N_CLASSES; i++) {
            result[i] = 1. / N_CLASSES;
        }
    } else {
        for (i = 0; i < N_CLASSES; i++) {
            result[i] = nums[i] / sum;
        }
    }
}

void compute(int *classes, double features[N_FEATURES]) {
    {{ tree | indent(4, True) }}
}

int predict(double features[N_FEATURES]) {
    int i;
    int classes[N_CLASSES];
    for (i = 0; i < N_CLASSES; i++) {
        classes[i] = 0;
    }
    compute(classes, features);
    return find_max(classes);
}

void predict_proba(double *result, double features[N_FEATURES]) {
    int i;
    int classes[N_CLASSES];
    for (i = 0; i < N_CLASSES; i++) {
        classes[i] = 0;
    }
    compute(classes, features);
    norm_vals(result, classes);
}

int main(int argc, const char *argv[]) {

    /* Features: */
    double features[argc-1];
    for (int i = 1; i < argc; i++) {
        features[i-1] = atof(argv[i]);
    }

    {% if is_test or to_json %}
    /* Get JSON: */
    double probabilities[N_CLASSES];
    predict_proba(probabilities, features);
    printf("{\"predict\": %d, \"predict_proba\": [", predict(features));
    for (int i = 0; i < N_CLASSES; i++) {
        printf("%.6f", probabilities[i]);
        if (i < (N_CLASSES - 1)) {
            printf(",");
        }
    }
    printf("]}");
    {% else %}
    /* Get class prediction: */
    printf("Predicted class: #%d\n", predict(features));

    /* Get class probabilities: */
    double probabilities[N_CLASSES];
    predict_proba(probabilities, features);
    for (int i = 0; i < N_CLASSES; i++) {
        printf("Probability of class #%d: %.6f\n", i, probabilities[i]);
    }
    {% endif %}

    return 0;
}
{% endblock %}